<template>
    <div class="user-list">
        <h3>用户列表</h3>
        <el-button type="success" @click="handleCreateUser">创建用户</el-button>
        <el-table :data="tableData" style="width: 100%; margin-top: 15px;">
            <el-table-column prop="index" label="序号" width="100" />
            <el-table-column label="昵称" prop="user_name" />
            <el-table-column label="邮箱" prop="email" />
            <el-table-column label="手机号" prop="phone_number" />
            <el-table-column label="性别" prop="user_sex" />
            <el-table-column label="生日" prop="birthday" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" type="warning" @click="handleEdit(scope.$index, scope.row)">
                        编辑
                    </el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <div class="page">
            <el-pagination :page-size="pageSize" :pager-count="5" layout="prev, pager, next" :total="totalNum"
                @current-change="changePageFn" />
        </div>
    </div>
    <el-dialog v-model="dialogTableVisible" :title="dialogTitle" width="400" align-center="true">
        <el-form ref="ruleFormRef" style="max-width: 600px;" :model="ruleForm" status-icon label-width="auto"
            class="demo-ruleForm">
            <el-form-item label="昵称：" prop="user_name" class="form-item">
                <el-input v-model="ruleForm.user_name" type="text" placeholder="请输入昵称" style="width: 240px" />
            </el-form-item>
            <el-form-item label="邮箱：" prop="email" class="form-item">
                <el-input v-model="ruleForm.email" type="text" placeholder="请输入邮箱" style="width: 240px" />
            </el-form-item>
            <el-form-item label="手机号：" prop="phone_number" class="form-item">
                <el-input v-model="ruleForm.phone_number" type="text" placeholder="请输入手机号" style="width: 240px" />
            </el-form-item>
            <el-form-item v-if="dialogTitle === '创建用户'" label="密码：" prop="user_password" class="form-item">
                <el-input v-model="ruleForm.user_password" type="text" placeholder="请输入密码" style="width: 240px" />
            </el-form-item>
            <el-form-item label="性别：" prop="user_sex" class="form-item">
                <el-select v-model="ruleForm.user_sex" placeholder="请选择性别" style="width: 180px">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="生日：" prop="birthday" class="form-item">
                <el-date-picker v-model="ruleForm.birthday" type="date" placeholder="请选择日期" style="width: 180px" />
            </el-form-item>
            <el-form-item style="margin-left: 150px;margin-top: 30px;">
                <el-button type="success" @click="saveUser">
                    保存
                </el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { userList, } from '../../api/request'
import api from '@/api/http'
import { ElMessage, ElMessageBox } from 'element-plus'

// 定义接口，形容对象的结构
interface User {
    date: string
    user_name: string
    email: string
    phone_number: string
    user_password: string
    user_sex: string // 修改性别类型为string，与options中的value类型一致
    birthday: Date | null // 修改生日类型为Date或null
    user_id?: number | string
}

const dialogTableVisible = ref(false)
const dialogTitle = ref('创建用户') // 用于动态设置对话框标题
const ruleForm = ref<User>({
    date: '',
    user_name: '',
    email: '', 
    phone_number: '',
    user_password: '',
    user_sex: '',
    birthday: null,
    user_id: ''
})

const options = [
    {
        value: '男',
        label: '男',
    },
    {
        value: '女',
        label: '女',
    }
]

// 用户列表数据
const tableData = ref<User[]>([])

// 用户总数
let totalNum = ref(0)
let page = ref(1)
let pageSize = ref(10)

// 定义函数获取用户列表
const userListFn = async (page = 1, pageSize = 10) => {
    await userList({ page, pageSize }).then(
        content => {
            let { code, total, result } = content;
            if (code == 200) {
                let newArr = result.map((item: any, i: number) => {
                    item.index = i + 1;
                    return item
                })
                tableData.value = newArr;
                totalNum.value = total;
            }
        }
    )
}

// 处理创建用户
const handleCreateUser = () => {
    ruleForm.value = {
        date: '',
        user_name: '',
        email: '',
        phone_number: '',
        user_password: '',
        user_sex: '',
        birthday: null,
        user_id: ''
    };
    dialogTitle.value = '创建用户'; // 设置对话框标题为创建用户
    dialogTableVisible.value = true; // 显示对话框
}

// 点击编辑用户
const handleEdit = (index: number, row: User) => {
    ruleForm.value = { ...row } // 将当前行的数据赋值给ruleForm
    dialogTitle.value = '编辑用户' // 修改对话框标题为编辑用户
    dialogTableVisible.value = true
}

// 点击删除用户
const handleDelete = (index: number, row: any) => {
    let { user_id } = row;
    ElMessageBox.confirm(
        `是否删除这个用户?`,
        '提示',
        {
            distinguishCancelAndClose: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    )
        .then(async () => {
            await api.deleteUser({ user_id })
                .then(
                    content => {
                        let { code, msg } = content;
                        if (code != 200) {
                            ElMessage.error(msg)
                        } else {
                            tableData.value.splice(index, 1);
                            ElMessage.success('用户删除成功')
                        }
                    }
                )
        })
        .catch(() => {
            console.log("点击取消")
        })
}

// 保存用户信息
const saveUser = async () => {
    console.log(ruleForm.value);
    
    if (ruleForm.value.user_id) {
        // 更新用户
        await api.updateUser(ruleForm.value)
            .then(
                content => {
                    let { code, msg } = content;
                    if (code == 200) {
                        ElMessage.success('用户信息更新成功')
                        dialogTableVisible.value = false
                        userListFn(page.value, pageSize.value) // 重新加载用户列表
                    } else {
                        ElMessage.error(msg)
                    }
                }
            )
    } else {
        // 创建用户
        await api.createUser(ruleForm.value)
            .then(
                content => {
                    let { code, msg } = content;
                    if (code == 200) {
                        ElMessage.success('用户创建成功')
                        dialogTableVisible.value = false
                        userListFn(page.value, pageSize.value) // 重新加载用户列表
                    } else {
                        ElMessage.error(msg)
                    }
                }
            )
    }
}

// 点击分页时执行的函数
const changePageFn = (num: number) => {
    page.value = num;
    userListFn(page.value, pageSize.value);
}

// 初始化用户列表
userListFn(page.value, pageSize.value);

</script>

<style lang="scss">
.user-list {
    h3 {
        margin-bottom: 15px;
    }

}

.page {
    margin-top: 15px;
    background-color: #fff;
    padding: 10px 10px;
}

.demo-ruleForm {
    .form-item {
        margin-left: 20px;
    }
}
</style>
